package com.gbk.clickhouseservicesave.task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *@ClassName AsyncTaskConfig
 *@Author: gbk
 *@Description TODO:
 *@Version: 1.0
 */

@Configuration
@Slf4j
public class AsyncTaskConfig implements AsyncConfigurer {
    public static final String CH_EXE = "CH_EXE";
    public static final String DB_EXE = "DB_EXE";

    public static int corePoolSize = 10;
    public static int queueCapacity = 2000;

    static {
        corePoolSize = Runtime.getRuntime().availableProcessors();
    }

    /**
     * 默认线程池
     * @return
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setMaxPoolSize(corePoolSize*2);
        taskExecutor.setRejectedExecutionHandler(new RejectionExecutionHandlerImpl("default"));
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * 外部消息转换 线程池
     * @return
     */
    public Executor getMesgExchangeExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setMaxPoolSize(corePoolSize*2);
        taskExecutor.setRejectedExecutionHandler(new RejectionExecutionHandlerImpl("getMesgExchangeExecutor"));
        taskExecutor.initialize();
        return taskExecutor;
    }

    /**
     * 数据存储 线程池
     * @return
     */
    public Executor getDBExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setMaxPoolSize(corePoolSize*2);
        taskExecutor.setRejectedExecutionHandler(new RejectionExecutionHandlerImpl("getMesgExchangeExecutor"));
        taskExecutor.initialize();
        return taskExecutor;
    }
}
